<template>
  <div>
    <el-breadcrumb separator="/" style="margin-top: 20px; margin-bottom: 20px">
      <el-breadcrumb-item :to="{ path: '/manager/order/tackOut' }"
        >首页</el-breadcrumb-item
      >
      <el-breadcrumb-item :to="{ path: 'manager/person/set' }"
        >修改个人信息</el-breadcrumb-item
      >
    </el-breadcrumb>

    <el-dialog v-model="photoShowFlag">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>

    <el-dialog v-model="AddressShowFlag" title="地址信息添加">
      <el-form>
        <el-form-item label="地址">
          <el-input
            v-model="addressContent"
            type="textarea"
            placeholder="请填写地址信息"
          ></el-input>
        </el-form-item>
        <el-form-item fixed="right">
          <el-button type="info" @click="AddressShowFlag = false">取消</el-button>
          <el-button type="primary" @click="AddAddressB">确认</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-form :model="form" label-width="auto" style="max-width: 600px; margin-left: 20px">
      <el-form-item label="用户名（仅展示）">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="账号名（账号登录）">
        {{ form.username }}
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="form.phone" type="number" />
      </el-form-item>
      <el-form-item label="性别">
        <el-select-v2
          v-model="form.sex"
          :options="sexOptions"
          placeholder="请选择性别"
          size="large"
          style="width: 240px"
        />
      </el-form-item>

      <el-form-item label="金额">
        {{ form.money }}
      </el-form-item>

      <el-form-item label="金额充值">
        <el-button type="warning" @click="addMoney(20)">充值20</el-button>
        <el-button type="warning" @click="addMoney(50)">充值50</el-button>
        <el-button type="warning" @click="addMoney(100)">充值100</el-button>
        <el-button type="warning" @click="addMoney(1000)">充值1000</el-button>
      </el-form-item>

      <el-form-item label="地址">
        <el-input
          v-model="form.address"
          type="textarea"
          placeholder="请输入你的家庭地址"
        />
      </el-form-item>
      <el-form-item label="头像" :label-width="formLabelWidth">
        <el-upload
          v-model:file-list="fileList"
          action="/api/upload/img"
          :headers="tokenBody"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="hanleSuccess"
          limit="1"
          ><el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="外卖地址管理(外卖时使用)" :label-width="formLabelWidth">
        <el-button type="primary" size="small" @click="addAddress">新增</el-button>

        <el-table :data="tableData" style="width: 100%" height="140px">
          <el-table-column fixed prop="address" label="地址" width="350" />
          <el-table-column fixed="right" label="操作" width="120">
            <template #default="scope">
              <el-button
                link
                type="primary"
                size="small"
                @click="delAddress(scope.row.addressId)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">保存信息</el-button>
        <el-button>Cancel</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import { ElMessage, UploadFile } from "element-plus";
import type { UploadProps, UploadUserFile } from "element-plus";
import axios from "axios";
const form = reactive({
  name: "",
  username: "",
  sex: "神秘",
  img: "",
  realImg: "",
  address: "",
  phone: "",
  money: 0,
});
const photoShowFlag = ref(false);
const dialogImageUrl = ref("");
const token = localStorage.getItem("student_auth_token");
const tokenBody = ref({
  token: token,
});
const fileList = ref<UploadUserFile[]>([]);

const formLabelWidth = "150px";
const sexOptions = [
  {
    label: "女",
    value: "女",
  },
  {
    label: "男",
    value: "男",
  },
  {
    label: "神秘",
    value: "神秘",
  },
];
const AddressShowFlag = ref(false);
const addressContent = ref("");
// do not use same name with ref
const delAddress = (id) => {
  axios
    .get("/api/userAddress/del/" + id, {
      headers: {
        token: token,
      },
    })
    .then((res) => {
      if (res.data.success) {
        ElMessage({
          type: "success",
          message: "删除成功",
        });
      } else {
        ElMessage({
          type: "error",
          message: "删除失败",
        });
      }
      getUserAddress();
    })
    .catch((err) => {});
};

const addAddress = () => {
  AddressShowFlag.value = true;
  addressContent.value = "";
};
const tableData = ref([]);

const getUserAddress = () => {
  axios
    .get("/api/userAddress/select", {
      headers: {
        token: token,
      },
    })
    .then((res) => {
      // console.log(res);
      tableData.value = res.data.message;
    })
    .catch((err) => {});
};
getUserAddress();
const AddAddressB = () => {
  if (addressContent.value == "") {
    ElMessage({
      type: "error",
      message: "地址不能为空",
    });
    return;
  }
  const flag = ref(true);
  tableData.value.forEach((el) => {
    if (el.address == addressContent.value) {
      ElMessage({
        type: "warning",
        message: "地址不可以重复",
      });
      flag.value = false;
    }
  });
  if (!flag.value) {
    return;
  }
  axios
    .get("/api/userAddress/insert?address=" + addressContent.value, {
      headers: {
        token: token,
      },
    })
    .then((res) => {
      if (res.data.success) {
        ElMessage({
          type: "success",
          message: "新增成功",
        });
      } else {
        ElMessage({
          type: "error",
          message: "新增失败",
        });
      }
      AddressShowFlag.value = false;
      getUserAddress();
    })
    .catch((err) => {});
};
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
  fileList.value = [];
};
const hanleSuccess: UploadProps["onSuccess"] = (res) => {
  const url = res.message;
  fileList.value = [];
  fileList.value.push({
    name: "hhe",
    url: res.message,
  });
  form.img = res.message;
};

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  photoShowFlag.value = true;
};

const onSubmit = () => {
  // console.log("submit!");
  if (form.name == "") {
    ElMessage({
      type: "error",
      message: "账户名称不能为空",
    });
  } else if (form.username == "") {
    ElMessage({
      type: "error",
      message: "用户名不能为空",
    });
  } else if (form.sex == "") {
    ElMessage({
      message: "性别不能为空",
      type: "error",
    });
  } else if (form.phone == "" || form.phone.length != 11) {
    ElMessage({
      message: "电话不能为空,且长度11位",
      type: "error",
    });
  } else if (form.address == "") {
    ElMessage({
      type: "error",
      message: "地址不能为空",
    });
  } else {
    const req = {
      name: form.name,
      address: form.address,
      phone: form.phone,
      sex: form.sex,
      img: form.img,
    };
    axios
      .post("/api/auth/update/user", req, {
        headers: {
          token: token,
        },
      })
      .then((res) => {
        // console.log("code line-159 \n\r😃 res:\n\r", res);
        if (res.data.success) {
          ElMessage({
            type: "success",
            message: "个人信息修改成功",
          });
        } else {
          ElMessage({
            type: "error",
            message: "修改失败",
          });
        }
        GetUserInfo();
      })
      .catch((err) => {
        // console.log("code line-163 \n\r😊 err:\n\r", err);
      });
  }
};

const GetUserInfo = () => {
  axios
    .get("/api/auth/userinfo", {
      headers: {
        token: token,
      },
    })
    .then((res) => {
      // console.log("code line-47 \n\r😔 res:\n\r", res);
      if (res.data.success) {
        const msg = res.data.message;
        form.username = msg.username;
        form.name = msg.name;
        form.sex = msg.sex ? msg.sex : "";
        form.money = msg.money;
        if (msg.img) {
          form.img = msg.img;

          fileList.value = [];
          fileList.value.push({
            name: "hhe",
            url: msg.img,
          });
        }

        form.address = msg.address ? msg.address : "";
        form.phone = msg.phone ? msg.phone : "";
      }
    })
    .catch((err) => {
      // console.log("code line-51 \n\r😆 err:\n\r", err);
    });
};
GetUserInfo();

const addMoney = (num) => {
  axios
    .get("/api/auth/add/money/" + num, {
      headers: {
        token: token,
      },
    })
    .then((res) => {
      // console.log("code line-359 \n\r😐 res:\n\r", res);
      if (res.data.success) {
        ElMessage({
          type: "success",
          message: "充值成功",
        });
      } else {
        ElMessage({
          type: "error",
          message: "充值失败",
        });
      }
      GetUserInfo();
    })
    .catch((err) => {});
};
</script>
